import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select,
  message,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { Link, useSearchParams } from "react-router-dom";
import "./index.scss";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import { useEffect, useState } from "react";
import { createArticleAPI, getArticleDetailAPI, editArticleAPI } from "@/apis";
import { useRef } from "react";
import { useChannelList } from "@/hooks/useChannel";

const { Option } = Select;

const Publish = () => {
  const { channelList } = useChannelList();
  const [form] = Form.useForm();

  const onFinish = async (formValue) => {
    if (type !== imageList.length) {
      message.warning("封面数量与选择的图片数量不一致");
      return;
    }
    const { content, title, channel_id } = formValue;
    const params = {
      title,
      channel_id,
      cover: {
        type: type,
        images: imageList.map((e) =>
          e.response ? e.response.data.url : e.url
        ),
      },
      content,
    };
    if (id) {
      params.id = id;
      await editArticleAPI(params);
      message.success("编辑文章成功");
    } else {
      await createArticleAPI(params);
      message.success("发布文章成功");
    }

    // 重置表单
    form.resetFields();
    // 重置图片列表和封面类型
    setImageList([]);
    setType(1);
  };

  const quillRef = useRef(null);
  const [imageList, setImageList] = useState([]);
  const onChange = (info) => {
    setImageList(info.fileList);
  };

  const [type, setType] = useState(1);
  const onTypeChange = (e) => {
    setType(e.target.value);
  };
  //回填表单
  const [searParams] = useSearchParams();
  const id = searParams.get("id");
  useEffect(() => {
    if (id) {
      const getDetail = async () => {
        const res = await getArticleDetailAPI(id);
        form.setFieldsValue({
          ...res.data,
          type: res.data.cover.type,
        });
        setImageList(
          res.data.cover.images.map((e) => ({
            url: e,
          }))
        );
        setType(res.data.cover.type);
      };
      getDetail();
    }
  }, [id, form]);

  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb
            items={[
              { title: <Link to={"/home"}>首页</Link> },
              { title: `${id ? "编辑文章" : "发布文章"}` },
            ]}
          />
        }
      >
        <Form
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1 }}
          onFinish={onFinish}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: "请输入文章标题" }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: "请选择文章频道" }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {channelList && channelList.length > 0 ? (
                channelList.map((item) => (
                  <Option key={item.id} value={item.id}>
                    {item.name}
                  </Option>
                ))
              ) : (
                <Option value="">暂无频道数据</Option>
              )}
            </Select>
          </Form.Item>
          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={onTypeChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {/* 
              listType: 决定选择文件框的外观样式
              showUploadList: 控制显示上传列表
            */}
            {type > 0 && (
              <Upload
                listType="picture-card"
                showUploadList
                action={"http://geek.itheima.net/v1_0/upload"}
                name="image"
                onChange={onChange}
                maxCount={type}
                fileList={imageList}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: "请输入文章内容" }]}
          >
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
              ref={quillRef} // 添加 ref
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {id ? "编辑" : "发布"}文章
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Publish;
